<template>
	<view class="cpk-detail">
		<view v-if="detail" class="card">
			<view class="header">
				<image :src="detail.logo" class="logo" mode="aspectFit" />
				<div class="header-text">
					<view class="title">{{ detail.name }}</view>
					<div class="features">{{ detail.features }}</div>
				</div>
				<view class="amount">{{ detail.creditLimit }}<text>最高额度</text></view>
			</view>
			<view class="info-row">
				<view class="info-block">
					<view class="info-value">{{ detail.annualInterestRate }}</view>
					<view class="info-title">年利率</view>
				</view>
				<view class="info-block">
					<view class="info-value">{{ detail.loanTerm }}</view>
					<view class="info-title">可借款期限</view>
				</view>
				<view class="info-block">
					<view class="info-value">{{ detail.passRate }}</view>
					<view class="info-title">通过率</view>
				</view>
			</view>
		</view>

		<!-- 佣金说明 -->
		<view class="commission-section" v-if="detail.rebateVip">
			<view class="section-title">佣金说明</view>
			<view class="commission-table">
				<!-- 表头 -->
				<view class="table-row table-header">
					<view class="table-cell cell-title">项目</view>
					<view class="table-cell cell-vip">VIP会员</view>
					<view class="table-cell cell-svip">SVIP会员</view>
				</view>
				<!-- 正常返佣 -->
				<view class="table-row">
					<view class="table-cell cell-title">正常返佣</view>
					<view class="table-cell cell-vip">{{ detail.rebateVip }}</view>
					<view class="table-cell cell-svip">{{ detail.rebateSvip }}</view>
				</view>
				<!-- 推量返佣 -->
				<view class="table-row">
					<view class="table-cell cell-title">推量返佣</view>
					<view class="table-cell cell-vip-cond">
						<view class="cond">{{ detail.pushRebateCountVip }}</view>
						<view class="money">{{ detail.pushRebateVip }}</view>
					</view>
					<view class="table-cell cell-svip-cond">
						<view class="cond">{{ detail.pushRebateCountSvip }}</view>
						<view class="money">{{ detail.pushRebateSvip }}</view>
					</view>
				</view>
			</view>
			<view class="commission-desc">
				<rich-text :nodes="detail.commissionDescription"></rich-text>
			</view>
		</view>
		<!-- 准入区域 -->
		<view class="commission-section" style="margin-bottom: 200rpx;">
			<view class="section-title">准入区域</view>
			<view class="zrqy-text">产品区域：{{ getAccessArea() }}</view>
			<view class="commission-desc">
				<rich-text :nodes="detail.description"></rich-text>
			</view>
		</view>
		<view class="footer-btn-fixed">
			<button class="contact-btn" @click="lxkfClick">联系客服</button>
			<button class="apply-btn" @click="handleApply">点击申请</button>
		</view>
		
		<!-- 申请弹出框 -->
		<view class="apply-modal" v-if="showApplyModal" @click="closeApplyModal">
			<view class="modal-content" @click.stop>
				<view class="modal-header">
					<text class="modal-title">产品申请</text>
					<text class="close-btn" @click="closeApplyModal">×</text>
				</view>
				<view class="modal-body">
					<image 
						:src="detail.qrCode" 
						class="product-image" 
						mode="aspectFit"
						@longpress="saveImage"
						:data-src="detail.qrCode"
					/>
					<view class="save-tip">长按图片进行保存</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		wechatConfig
	} from '@/api/wechat-config.js';

	export default {
		data() {
			return {
				guid: '',
				detail: null,
				showApplyModal: false
			}
		},
		computed: {
			// 从 Vuex 获取登录状态
			isLoggedIn() {
				return this.$store.state.user.isLoggedIn;
			},
			userInfo() {
				console.log(this.$store.state.user.userInfo)
				return this.$store.state.user.userInfo;
			}
		},
		onLoad(options) {
			this.guid = options.guid
			this.getDetail()
		},
		methods: {
			async getDetail() {
				try {
					const res = await this.$api.getCpkDataDetails(this.guid)
					if (res.succ) {
						this.detail = res.data
						console.log('this.detail', this.detail)
					}
				} catch (e) {
					uni.showToast({
						title: '获取详情失败',
						icon: 'none'
					})
				}
			},
			getAccessArea() {
				if (!this.detail) return '全国';

				const province = this.detail.accessProvince || '';
				const city = this.detail.accessCity || '';

				// 如果省份和城市都为空，显示全国
				if (!province && !city) {
					return '全国';
				}

				// 如果只有省份，显示省份
				if (province && !city) {
					return province;
				}

				// 如果只有城市，显示城市
				if (!province && city) {
					return city;
				}

				// 如果省份和城市都有，显示省份/城市
				return `${province}/${city}`;
			},
			// 联系客服
			async lxkfClick() {
				// 检查登录状态
				if (!this.isLoggedIn) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
					// 跳转到登录页面
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/login/login'
						});
					}, 1500);
					return;
				}

				// 构建产品信息
				const productInfo = {
					name: this.detail?.name || '产品',
					description: this.detail?.description || '',
					creditLimit: this.detail?.creditLimit || '',
					annualInterestRate: this.detail?.annualInterestRate || ''
				};

				// #ifdef MP-WEIXIN
				// 微信小程序环境下使用优化的方式
				this.handleWechatMiniProgram(productInfo);
				// #endif

				// #ifdef H5
				// H5环境下直接跳转
				const wechatLink = 'https://work.weixin.qq.com/kfid/kfc4b0a7189e6c317ea';
				const params = [];
				params.push(`product_name=${encodeURIComponent(productInfo.name)}`);
				params.push(`credit_limit=${encodeURIComponent(productInfo.creditLimit)}`);
				params.push(`interest_rate=${encodeURIComponent(productInfo.annualInterestRate)}`);

				const fullLink = `${wechatLink}?${params.join('&')}`;
				window.open(fullLink, '_blank');
				// #endif

				// #ifdef APP-PLUS
				// App环境下使用plus.runtime.openURL
				const appWechatLink = 'https://work.weixin.qq.com/kfid/kfc4b0a7189e6c317ea';
				const appParams = [];
				appParams.push(`product_name=${encodeURIComponent(productInfo.name)}`);
				appParams.push(`credit_limit=${encodeURIComponent(productInfo.creditLimit)}`);
				appParams.push(`interest_rate=${encodeURIComponent(productInfo.annualInterestRate)}`);

				const appFullLink = `${appWechatLink}?${appParams.join('&')}`;
				plus.runtime.openURL(appFullLink, (err) => {
					if (err) {
						console.error('打开企业微信失败:', err);
						this.copyLink(appFullLink);
					}
				});
				// #endif
			},
           		   // 点击申请
		   handleApply() {
			   // 检查登录状态
			   if (!this.isLoggedIn) {
			   	uni.showToast({
			   		title: '请先登录',
			   		icon: 'none'
			   	});
			   	// 跳转到登录页面
			   	setTimeout(() => {
			   		uni.redirectTo({
			   			url: '/pages/login/login'
			   		});
			   	}, 1500);
			   	return;
			   }
			   // 判断是否开通会员
			   if(this.userInfo.authStatus == '0' && (this.detail.memberOnly == 1 || this.detail.memberOnly == '1') ) { // 普通用户
			   	this.showMembershipModal();
			   	return;
			   }
			   
			   // 会员用户继续原有逻辑
			   this.processApply();
		   },
			// 显示会员提示弹出框
			showMembershipModal() {
				uni.showModal({
					title: '会员专享功能',
					content: '此功能仅对会员用户开放，开通即解锁平台所有产品进件特权！',
					confirmText: '立即开通',
					cancelText: '暂不开通',
					success: (res) => {
						if (res.confirm) {
							// 跳转到会员开通页面
							uni.navigateTo({
								url: '/pages/membership/membership'
							});
						}
					}
				});
			},
			
			// 处理申请逻辑（会员用户）
			processApply() {
				// 展示产品qrCode图片
				if (this.detail && this.detail.qrCode) {
					// 显示自定义弹出框
					this.showApplyModal = true;
				} else {
					uni.showToast({
						title: '暂无产品图片',
						icon: 'none'
					});
				}
			},
			
			// 关闭申请弹出框
			closeApplyModal() {
				this.showApplyModal = false;
			},
			
			// 保存图片
			saveImage(e) {
				const imageSrc = e.currentTarget.dataset.src;
				if (!imageSrc) {
					uni.showToast({
						title: '图片地址无效',
						icon: 'none'
					});
					return;
				}
				
				// #ifdef MP-WEIXIN
				// 微信小程序环境 - 先检查权限
				uni.getSetting({
					success: (res) => {
						if (res.authSetting['scope.writePhotosAlbum'] === false) {
							// 用户之前拒绝了权限，引导用户开启
							uni.showModal({
								title: '需要相册权限',
								content: '保存图片需要相册权限，请在设置中开启',
								confirmText: '去设置',
								success: (modalRes) => {
									if (modalRes.confirm) {
										uni.openSetting();
									}
								}
							});
						} else {
							// 有权限或未设置过，直接保存
							this.downloadAndSaveImage(imageSrc);
						}
					},
					fail: () => {
						// 获取设置失败，直接尝试保存
						this.downloadAndSaveImage(imageSrc);
					}
				});
				// #endif
				
				// #ifdef H5
				// H5环境
				uni.showToast({
					title: 'H5环境暂不支持保存图片',
					icon: 'none'
				});
				// #endif
				
				// #ifdef APP-PLUS
				// App环境
				this.downloadAndSaveImage(imageSrc);
				// #endif
			},
			
			// 下载并保存图片
			downloadAndSaveImage(imageSrc) {
				uni.downloadFile({
					url: imageSrc,
					success: (res) => {
						if (res.statusCode === 200) {
							uni.saveImageToPhotosAlbum({
								filePath: res.tempFilePath,
								success: () => {
									uni.showToast({
										title: '图片已保存到相册',
										icon: 'success'
									});
								},
								fail: (err) => {
									console.error('保存图片失败:', err);
									if (err.errMsg.includes('auth deny')) {
										uni.showModal({
											title: '保存失败',
											content: '需要您授权保存图片到相册，请在设置中开启相册权限',
											confirmText: '去设置',
											success: (res) => {
												if (res.confirm) {
													uni.openSetting();
												}
											}
										});
									} else {
										uni.showToast({
											title: '保存失败',
											icon: 'none'
										});
									}
								}
							});
						}
					},
					fail: (err) => {
						console.error('下载图片失败:', err);
						uni.showToast({
							title: '图片下载失败',
							icon: 'none'
						});
					}
				});
			},
			
			// 处理微信小程序环境
			handleWechatMiniProgram(productInfo) {
				// 使用 wx.openCustomerServiceChat 打开微信客服
				this.openCustomerServiceChat(productInfo);
			},

			// 使用 wx.openCustomerServiceChat 打开微信客服
			openCustomerServiceChat(productInfo) {
				// 构建客服消息内容
				const message =
					`咨询产品：${productInfo.name}\n最高额度：${productInfo.creditLimit}\n年利率：${productInfo.annualInterestRate}`;

				// 检查是否支持 openCustomerServiceChat
				if (typeof wx.openCustomerServiceChat === 'function') {
					// 使用 wx.openCustomerServiceChat 打开客服会话
					wx.openCustomerServiceChat({
						extInfo: {
							url: 'https://work.weixin.qq.com/kfid/kfc4b0a7189e6c317ea'
						},
						corpId: 'ww9cf0abfb03da37dd', // 企业微信ID
						success: () => {
							console.log('成功打开微信客服');
							uni.showToast({
								title: '正在打开客服',
								icon: 'success'
							});
						},
						fail: (err) => {
							console.log('打开微信客服失败:', err);
							// 根据错误码进行不同的降级处理
							if (err.errCode === 6) {
								// errCode 6: 未绑定企业微信客服会话
								uni.showModal({
									title: '功能暂未开通',
									content: '企业微信客服会话功能暂未开通，我们将为您复制客服链接，请手动打开进行咨询。',
									confirmText: '复制链接',
									cancelText: '取消',
									success: (res) => {
										if (res.confirm) {
											this.copyLink(
												'https://work.weixin.qq.com/kfid/kfc4b0a7189e6c317ea'
												);
										}
									}
								});
							} else {
								// 其他错误，直接复制链接
								this.showCopyDialog('https://work.weixin.qq.com/kfid/kfc4b0a7189e6c317ea',
									productInfo);
							}
						}
					});
				} else {
					// 如果不支持，直接复制链接
					this.showCopyDialog('https://work.weixin.qq.com/kfid/kfc4b0a7189e6c317ea', productInfo);
				}
			},



			// 显示复制对话框
			showCopyDialog(fullLink, productInfo) {
				uni.showModal({
					title: '申请产品',
					content: `您正在申请产品：${productInfo.name}\n\n无法直接打开客服会话，我们将为您复制客服链接，请手动打开进行咨询。`,
					confirmText: '复制链接',
					cancelText: '取消',
					success: (res) => {
						if (res.confirm) {
							this.copyLink(fullLink);
						}
					}
				});
			},



			// 复制链接到剪贴板
			copyLink(link) {
				uni.setClipboardData({
					data: link,
					success: () => {
						uni.showToast({
							title: '客服链接已复制',
							icon: 'success',
							duration: 2000
						});

						// 延迟显示操作指引
						setTimeout(() => {
							uni.showModal({
								title: '操作指引',
								content: '1. 打开微信\n2. 粘贴链接到浏览器\n3. 进入客服页面进行咨询',
								showCancel: false,
								confirmText: '知道了'
							});
						}, 1000);
					},
					fail: () => {
						uni.showToast({
							title: '复制失败，请手动打开链接',
							icon: 'none'
						});
					}
				});
			}
		}
	}
</script>

<style lang="less">
	.cpk-detail {
		padding: 30rpx;

		.card {
			background: #fff;
			border-radius: 20rpx;
			box-shadow: 0 4rpx 16rpx #f5f5f5;
			padding: 20rpx;
			margin-bottom: 30rpx;

			.header {
				display: flex;
				align-items: center;

				.logo {
					width: 120rpx;
					height: 120rpx;
					margin-right: 26rpx;
					border-radius: 16rpx;
					background: #f8f8f8;
				}

				.header-text {
					flex: 1;
					display: flex;
					flex-direction: column;

					.title {
						color: #000;
						font-size: 36rpx;
						font-weight: bold;
					}

					.features {
						color: #333;
						font-size: 28rpx;
						margin-top: 20rpx;
					}

				}

				.amount {
					display: flex;
					flex-direction: column;
					align-items: center;
					font-size: 32rpx;
					color: #333;
					font-weight: bold;

					text {
						display: block;
						font-size: 24rpx;
						color: #888;
						margin-top: 18rpx;

					}
				}
			}

			.info-row {
				display: flex;
				justify-content: space-between;
				margin-top: 40rpx;

				.info-block {
					flex: 1;
					text-align: center;

					.info-value {
						color: #333;
						font-size: 32rpx;
						font-weight: bold;
					}

					.info-title {
						color: #333;
						font-size: 28rpx;
						margin-top: 10rpx;
					}
				}
			}
		}

		.commission-section {
			background: #fff;
			border-radius: 20rpx;
			box-shadow: 0 4rpx 16rpx #f5f5f5;
			padding: 30rpx;

			.section-title {
				font-size: 30rpx;
				font-weight: bold;
				margin-bottom: 20rpx;
			}

			.commission-table {
				border-radius: 16rpx;
				overflow: hidden;
				box-shadow: 0 4rpx 16rpx #f5f5f5;

				.table-row {
					display: flex;

					.table-cell {
						flex: 1;
						text-align: center;
						padding: 24rpx 0;
						font-size: 28rpx;
						border-bottom: 1px solid #ececec;
						border-right: 1px solid #ececec;
						background: #fff;
						display: flex;
						align-items: center;
						justify-content: center;

						&.cell-title {
							flex: 0 0 25%;
						}
					}

					.table-cell:last-child {
						border-right: none;
					}

					&.table-header {
						background: #f5f5f5;

						.table-cell {
							background: #f5f5f5;
							font-size: 28rpx;
						}
					}

					&:last-child .table-cell {
						border-bottom: none;
					}

					.cell-vip-cond,
					.cell-svip-cond {
						flex-direction: column;
						align-items: center;
						justify-content: center;
						padding: 18rpx 0;
						font-size: 28rpx;
						display: flex;
					}

					.cond {

						color: #333;
						margin-bottom: 20rpx;
						font-size: 28rpx;
					}

					.money {
						font-size: 28rpx;
					}
				}
			}
		}
	}

	.commission-desc {
		margin-top: 24rpx;
		color: #000;
		font-size: 28rpx;
		line-height: 1.7;
		word-break: break-all;
	}

	.zrqy-text {
		font-size: 28rpx;
		color: #000;
	}

	.footer-btn-fixed {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 999;
		background: #fff;
		padding: 16rpx 30rpx 32rpx 30rpx;
		box-shadow: 0 -2rpx 12rpx 0 rgba(0, 0, 0, 0.04);
		display: flex;
		gap: 20rpx;

		.contact-btn {
			display: flex;
			justify-content: center;
			align-items: center;
			flex: 1;
			height: 88rpx;
			background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
			color: #fff;
			border: none;
			border-radius: 44rpx;
			font-size: 28rpx;
		}

		.apply-btn {
			flex: 1;
			display: flex;
			justify-content: center;
			align-items: center;
			height: 88rpx;
			background: linear-gradient( 135deg, #F3B359 0%, #EC6A34 100%);
			color: #fff;
			border: none;
			border-radius: 44rpx;
			font-size: 28rpx;
		}
	}
	
	/* 申请弹出框样式 */
	.apply-modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.6);
		z-index: 1000;
		display: flex;
		align-items: center;
		justify-content: center;
		
		.modal-content {
			background: #fff;
			border-radius: 20rpx;
			width: 80%;
			max-width: 600rpx;
			overflow: hidden;
			
			.modal-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 30rpx;
				border-bottom: 1px solid #f0f0f0;
				
				.modal-title {
					font-size: 32rpx;
					font-weight: bold;
					color: #333;
				}
				
				.close-btn {
					font-size: 40rpx;
					color: #999;
					line-height: 1;
					cursor: pointer;
					padding: 10rpx;
				}
			}
			
			.modal-body {
				padding: 40rpx;
				text-align: center;
				
				.product-image {
					width: 100%;
					height: 400rpx;
					border-radius: 16rpx;
					margin-bottom: 30rpx;
				}
				
				.save-tip {
					font-size: 28rpx;
					color: #666;
					line-height: 1.5;
				}
			}
		}
	}
</style>